package com.sky.service.impl;

import com.sky.service.GeocodingService;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;




@Service
public class GeocodingServiceImpl implements GeocodingService {
    @Override
    public String getlocationbyadress(String address) {
        try {
            String apiKey = "34d78dea5ef31f53cf88ac0c17514c9f"; // 替换为你的高德API密钥

            String city = "江西"; // 城市
            String encodedAddress = URLEncoder.encode(address, "UTF-8");
            String encodedCity = URLEncoder.encode(city, "UTF-8");

            // 构造请求URL
            String urlString = "https://restapi.amap.com/v3/geocode/geo?key=" + apiKey +
                    "&address=" + encodedAddress + "&city=" + encodedCity;

            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析响应结果
            JSONObject jsonResponse = new JSONObject(response.toString());
            JSONArray geocodes = jsonResponse.getJSONArray("geocodes");
            if (geocodes.length() > 0) {
                JSONObject locationInfo = geocodes.getJSONObject(0);
                String location = locationInfo.getString("location");
               return location;
            } else {
                System.out.println("未找到经纬度信息");
                return "地理编码转化错误";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
